<template>
  <div class="main-layout">
    <template v-if="$route.path === '/prompts'">
      <router-view></router-view>
    </template>
    <template v-else-if="$route.path === '/dsl-examples'">
      <router-view></router-view>
    </template>
    <template v-else-if="$route.path === '/sql-templates'">
      <router-view></router-view>
    </template>
    <template v-else-if="$route.path === '/enum-config'">
      <router-view></router-view>
    </template>
    <template v-else-if="$route.path === '/synonym-config'">
      <router-view></router-view>
    </template>
    <template v-else-if="$route.path === '/rule-config'">
      <router-view></router-view>
    </template>
    <template v-else>
      <div class="chat-container">
        <div class="chat-header">
          <h1>智能问数小助手</h1>
        </div>
        <div class="chat-history" ref="chatHistory">
          <div v-for="(item, index) in chatHistory" :key="index" class="chat-item">
            <div class="user-message">
              <div class="message-content">{{ item.question }}</div>
              <div class="user-avatar">
                <span>Q</span>
              </div>
            </div>
            <div class="ai-answer" v-if="item.loading">
              <div class="ai-avatar">A</div>
              <div class="content">
                <div class="loading-box">
                  <div class="loading-text">{{ item.loadingText }}</div>
                  <div class="loading-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
              </div>
            </div>
            <div class="ai-answer" v-else-if="item.ambiguousSelection">
              <div class="ai-avatar">A</div>
              <div class="content">
                <div class="ambiguous-box">
                  <div class="ambiguous-intro">您提到的以下词语存在多种含义，请选择您想要的：</div>
                  <div v-for="(options, term) in item.ambiguousInfo" :key="term" class="ambiguous-item">
                    <div class="term-label">{{ term }}：</div>
                    <div class="options-list">
                      <button
                        v-for="(option, index) in options"
                        :key="index"
                        class="option-button"
                        @click="selectAmbiguousOption(item, term, option)"
                        :class="{ 'selected': item.selectedOptions && item.selectedOptions[term] === option }"
                      >
                        {{ formatOption(term, option) }}
                      </button>
                    </div>
                  </div>
                  <button 
                    class="confirm-button" 
                    @click="confirmAmbiguousSelections(item)"
                    :disabled="!canConfirmSelections(item)"
                  >
                    确认选择
                  </button>
                </div>
              </div>
            </div>
            <div class="ai-answer" v-else-if="item.data">
              <div class="ai-avatar">A</div>
              <div class="content">
                <div class="answer-box">
                  <div class="answer-intro">根据您的问题，查询结果如下：</div>
                  <condition-form
                    v-if="item.dsl && item.query_type"
                    :dsl="item.dsl"
                    :query-type="item.query_type"
                    @conditions-updated="handleConditionsUpdated"
                  />
                  <div class="data-display">
                    <table>
                      <thead>
                        <tr>
                          <th v-for="column in item.columns" :key="column">{{ column }}</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr v-for="(row, rowIndex) in item.data" :key="rowIndex">
                          <td v-for="column in item.columns" :key="column">{{ row[column] }}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="input-area">
          <input 
            v-model="question" 
            placeholder="请输入您的问题"
            @keyup.enter="sendQuestion"
            :disabled="loading"
          >
          <button 
            @click="sendQuestion" 
            :disabled="loading || !question.trim()"
          >
            {{ loading ? '请稍候...' : '发送' }}
          </button>
        </div>
      </div>
      <div class="side-panels">
        <div class="config-panel">
          <h3>💻 问数配置</h3>
          <div class="config-content">
            <button class="config-button" @click="goToPrompts">
              prompt 配置
            </button>
            <button class="config-button" @click="goToDslExamples">
              DSL 示例配置
            </button>
            <button class="config-button" @click="goToSqlTemplates">
              SQL 模板配置
            </button>
            <button class="config-button" @click="goToEnumConfig">
              枚举值配置
            </button>
            <button class="config-button" @click="goToSynonymConfig">
              同义词配置
            </button>
            <button class="config-button" @click="goToRuleConfig">
              规则配置
            </button>
          </div>
        </div>
        <div class="inspiration-panel">
          <h3>💡 问题灵感</h3>
          <div class="inspiration-list">
            <div 
              v-for="(item, index) in inspirations" 
              :key="index"
              class="inspiration-item"
              @click="selectInspiration(item)">
              {{ item }}
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
/* eslint-disable no-unused-vars */
import * as echarts from 'echarts'
import { API_BASE_URL } from './config'
import ConditionForm from './components/ConditionForm.vue'
/* eslint-enable no-unused-vars */

export default {
  name: 'App',
  components: {
    ConditionForm
  },
  data() {
    return {
      question: '',
      loading: false,
      error: null,
      chatHistory: [],  // 存储对话历史
      charts: [],        // 存储图表实例
      chartContainers: [],  // 存储图表容器引用
      baseUrl: API_BASE_URL,  // 使用配置中的 API_BASE_URL
      inspirations: [
        "24年KPI收入TOP10城市",
        "24年Q4收入大于1w的省份",
        "24年专业收入最少的5个城市",
        "本季度收入最佳产品LV3"
      ]
    }
  },
  methods: {
    formatNumber(value) {
      return value.toLocaleString()
    },
    
    isNumber(value) {
      return typeof value === 'number'
    },
    
    // 判断是否可以展示为图表
    canShowChart(columns, data) {
      // 至少要有两列数据
      if (!columns || columns.length < 2) {
        console.log('列数不足，不显示图表')
        return false
      }
      
      // 检查数据对象是否存在
      if (!data) {
        console.log('数据对象不存在')
        return false
      }
      
      // 检查是否有一列是数值类型
      let hasNumericColumn = false
      let numericColumnIndex = -1
      
      for (let i = 0; i < columns.length; i++) {
        const columnName = columns[i]
        if (!data[columnName] || !Array.isArray(data[columnName])) {
          console.log(`列 ${columnName} 的数据不正确`)
          continue
        }
        
        // 检查该列的第一个非空值是否为数字
        const firstValue = data[columnName].find(val => val !== null && val !== undefined)
        if (typeof firstValue === 'number') {
          hasNumericColumn = true
          numericColumnIndex = i
          break
        }
      }
      
      return hasNumericColumn ? numericColumnIndex : false
    },
    
    // 格式化选项显示
    // eslint-disable-next-line no-unused-vars
    formatOption(term, option) {
      const field = Object.keys(option)[0]
      const value = Object.values(option)[0].in[0]
      return `${term} 作为 ${value}(${field})`
    },

    // 检查是否可以确认选择
    canConfirmSelections(item) {
      return item.selectedOptions && 
             Object.keys(item.ambiguousInfo).length === Object.keys(item.selectedOptions).length
    },

    // 选择某个选项
    selectAmbiguousOption(item, term, option) {
      if (!item.selectedOptions) {
        item.selectedOptions = {}
      }
      item.selectedOptions[term] = option
    },

    // 确认所有选择并继续查询
    async confirmAmbiguousSelections(item) {
      // 更新 field_info
      const updatedFieldInfo = typeof item.fieldInfo === 'string' ? 
        JSON.parse(item.fieldInfo) : 
        { ...item.fieldInfo }
      
      // 将选择的选项合并到 field_info 中
      Object.entries(item.selectedOptions).forEach(([term, option]) => {
        const field = Object.keys(option)[0]
        const value = option[field].in[0]
        updatedFieldInfo[term] = {
          [field]: {
            in: [value]
          }
        }
      })

      // 更新加载状态
      item.ambiguousSelection = false
      item.loading = true
      item.loadingText = '结果生成中'

      try {
        // 调用 post-ask-number 接口，将 field_info 转换为字符串
        const postResponse = await fetch(`${this.baseUrl}/api/post-ask-number`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            query: item.query,
            semantic_info: item.semanticInfo,
            field_info: JSON.stringify(updatedFieldInfo),  // 将对象转换为字符串
            query_type: item.queryType
          })
        })

        if (!postResponse.ok) {
          throw new Error(`HTTP error! status: ${postResponse.status}`)
        }

        const responseData = await postResponse.json()
        
        // 处理响应数据
        if (!responseData.data || !responseData.data.columns || !responseData.data.data) {
          throw new Error('响应数据格式不正确')
        }
        
        const { columns, data } = responseData.data
        
        // 转换数据格式
        const tableData = []
        const rowCount = data[columns[0]].length
        
        for (let i = 0; i < rowCount; i++) {
          const row = {}
          columns.forEach(col => {
            row[col] = data[col][i]
          })
          tableData.push(row)
        }
        
        // 更新对话项数据
        Object.assign(item, {
          loading: false,
          data: tableData,
          columns: columns,
          dsl: responseData.dsl,
          query_type: responseData.query_type
        })

        // 处理图表显示
        this.handleChartDisplay(item, columns, data)
      } catch (error) {
        console.error('请求失败:', error)
        Object.assign(item, {
          loading: false,
          error: `请求失败: ${error.message}`
        })
      }
    },

    async handleSubmit() {
      if (!this.question.trim() || this.loading) return
      
      console.log('发送问题:', this.question)
      this.loading = true
      
      const chatItem = {
        question: this.question,
        loading: true,
        loadingText: '问题智能分析中',  // 添加加载文本
        data: null,
        columns: [],
        dsl: null,
        query_type: null,
        showChart: true
      }
      this.chatHistory.push(chatItem)
      
      const currentQuestion = this.question
      this.question = ''
      
      try {
        // 第一阶段：调用 pre-ask-number
        const preResponse = await fetch(`${this.baseUrl}/api/pre-ask-number`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ query: currentQuestion })
        })

        if (!preResponse.ok) {
          throw new Error(`HTTP error! status: ${preResponse.status}`)
        }

        const preData = await preResponse.json()
        console.log('pre-ask-number response:', preData)  // 添加日志
        const index = this.chatHistory.length - 1

        // 检查是否存在歧义信息并且不为空对象
        if (preData.ambiguous_info && Object.keys(preData.ambiguous_info).length > 0) {
          console.log('Found ambiguous info:', preData.ambiguous_info)
          // 显示歧义选择界面
          this.chatHistory[index] = {
            ...chatItem,
            loading: false,
            ambiguousSelection: true,
            ambiguousInfo: preData.ambiguous_info,
            query: preData.query,
            semanticInfo: preData.semantic_info,
            fieldInfo: typeof preData.field_info === 'string' ? JSON.parse(preData.field_info) : preData.field_info,  // 解析字符串
            queryType: preData.query_type,
            selectedOptions: {}
          }
          return
        }

        // 如果没有歧义，继续原来的流程
        this.chatHistory[index].loadingText = '结果生成中'

        // 第二阶段：调用 post-ask-number
        const postResponse = await fetch(`${this.baseUrl}/api/post-ask-number`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            query: preData.query,
            semantic_info: preData.semantic_info,
            field_info: typeof preData.field_info === 'string' ? 
              preData.field_info : 
              JSON.stringify(preData.field_info),  // 确保 field_info 是字符串
            query_type: preData.query_type
          })
        })

        if (!postResponse.ok) {
          throw new Error(`HTTP error! status: ${postResponse.status}`)
        }

        const responseData = await postResponse.json()
        
        if (!responseData.data || !responseData.data.columns || !responseData.data.data) {
          throw new Error('响应数据格式不正确')
        }
        
        const { columns, data } = responseData.data
        
        // 转换数据格式
        const tableData = []
        const rowCount = data[columns[0]].length
        
        for (let i = 0; i < rowCount; i++) {
          const row = {}
          columns.forEach(col => {
            row[col] = data[col][i]
          })
          tableData.push(row)
        }
        
        // 更新对话项数据
        this.chatHistory[index] = {
          ...chatItem,
          loading: false,
          data: tableData,
          columns: columns,
          dsl: responseData.dsl,
          query_type: responseData.query_type
        }
        
        // 检查是否可以显示图表
        const numericColumnIndex = this.canShowChart(columns, data)
        
        if (numericColumnIndex !== false) {
          await this.$nextTick()
          const chartContainer = document.createElement('div')
          chartContainer.style.width = '100%'
          chartContainer.style.height = '400px'
          chartContainer.className = 'chart-container'
          
          const answerBox = document.querySelector(`.chat-item:nth-child(${index + 1}) .answer-box`)
          if (answerBox) {
            answerBox.appendChild(chartContainer)
            const chart = echarts.init(chartContainer)
            
            const option = {
              title: {
                text: '', //图表的标题待补充
                left: 'center',
                textStyle: {
                  color: '#1565c0',
                  fontSize: 16,
                  fontWeight: 500
                }
              },
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  type: 'shadow'
                },
                formatter: function(params) {
                  return `${params[0].name}<br/>${params[0].seriesName}: ${params[0].value.toLocaleString()}`
                }
              },
              grid: {
                top: '15%',
                left: '40px',
                right: '40px',
                bottom: '15%',
                containLabel: true
              },
              dataZoom: [{
                type: 'slider',
                show: true,
                start: 0,
                end: Math.min(100, Math.ceil(5 / tableData.length * 100)),
                bottom: 10
              }, {
                type: 'inside',
                start: 0,
                end: Math.min(100, Math.ceil(5 / tableData.length * 100))
              }],
              xAxis: {
                type: 'category',
                data: data[columns[0]],
                axisLabel: {
                  interval: 0,
                  rotate: 30,
                  color: '#666',
                  fontSize: 12
                },
                axisTick: {
                  alignWithLabel: true
                },
                axisLine: {
                  lineStyle: {
                    color: '#ddd'
                  }
                }
              },
              yAxis: {
                type: 'value',
                name: '收入',
                nameTextStyle: {
                  color: '#666',
                  fontSize: 12
                },
                axisLabel: {
                  color: '#666',
                  fontSize: 12,
                  formatter: function(value) {
                    return value.toLocaleString()
                  }
                },
                splitLine: {
                  lineStyle: {
                    color: '#eee'
                  }
                }
              },
              series: [{
                name: '收入',
                data: data[columns[1]],
                type: 'bar',
                barWidth: '40%',
                barMaxWidth: 60,
                barMinWidth: 15,
                itemStyle: {
                  color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                      offset: 0,
                      color: '#83bff6'
                    }, {
                      offset: 1,
                      color: '#1890ff'
                    }]
                  },
                  borderRadius: [3, 3, 0, 0]
                },
                label: {
                  show: true,
                  position: 'top',
                  fontSize: 12,
                  color: '#666',
                  formatter: function(params) {
                    return params.value.toLocaleString()
                  }
                },
                emphasis: {
                  itemStyle: {
                    color: {
                      type: 'linear',
                      x: 0,
                      y: 0,
                      x2: 0,
                      y2: 1,
                      colorStops: [{
                        offset: 0,
                        color: '#1890ff'
                      }, {
                        offset: 1,
                        color: '#83bff6'
                      }]
                    }
                  }
                }
              }]
            }
            
            chart.setOption(option)
            this.charts[index] = chart
            
            window.addEventListener('resize', () => {
              chart.resize()
            })
          }
        } else {
          console.log('数据不适合显示图表，仅显示表格')
        }
        
        this.$refs.chatHistory.scrollTop = this.$refs.chatHistory.scrollHeight
        
      } catch (error) {
        console.error('请求失败详细信息:', error)
        const index = this.chatHistory.length - 1
        this.chatHistory[index] = {
          ...chatItem,
          loading: false,
          error: `请求失败: ${error.message}`
        }
      } finally {
        this.loading = false  // 结束加载
      }
    },
    
    // 新增选择灵感的方法
    selectInspiration(question) {
      this.question = question
    },
    goToPrompts() {
      this.$router.push({ name: 'Prompts' })
    },
    goToDslExamples() {
      this.$router.push({ name: 'DslExamples' })
    },
    goToSqlTemplates() {
      this.$router.push({ name: 'SqlTemplates' })
    },
    goToEnumConfig() {
      this.$router.push({ name: 'EnumConfig' })
    },
    goToSynonymConfig() {
      this.$router.push({ name: 'SynonymConfig' })
    },
    goToRuleConfig() {
      this.$router.push('/rule-config')
    },
    async sendQuestion() {
      await this.handleSubmit()  // 使用现有的 handleSubmit 方法
    },
    handleConditionsUpdated(result) {
      if (result.data && result.data.columns && result.data.data) {
        const { columns, data } = result.data
        
        // 转换数据格式
        const tableData = []
        const rowCount = data[columns[0]].length
        
        for (let i = 0; i < rowCount; i++) {
          const row = {}
          columns.forEach(col => {
            row[col] = data[col][i]
          })
          tableData.push(row)
        }
        
        // 创建新的对话项
        const newChatItem = {
          question: '修改查询条件后的结果：',
          loading: false,
          data: tableData,
          columns: columns,
          dsl: result.dsl,
          query_type: result.query_type,
          showChart: true
        }
        
        this.chatHistory.push(newChatItem)
        
        // 检查是否可以显示图表
        const numericColumnIndex = this.canShowChart(columns, data)
        
        if (numericColumnIndex !== false) {
          this.$nextTick(() => {
            const chartContainer = document.createElement('div')
            chartContainer.style.width = '100%'
            chartContainer.style.height = '400px'
            chartContainer.className = 'chart-container'
            
            const index = this.chatHistory.length - 1
            const answerBox = document.querySelector(`.chat-item:nth-child(${index + 1}) .answer-box`)
            if (answerBox) {
              answerBox.appendChild(chartContainer)
              const chart = echarts.init(chartContainer)
              
              const option = {
                title: {
                  text: '',
                  left: 'center',
                  textStyle: {
                    color: '#1565c0',
                    fontSize: 16,
                    fontWeight: 500
                  }
                },
                tooltip: {
                  trigger: 'axis',
                  axisPointer: {
                    type: 'shadow'
                  },
                  formatter: (params) => {
                    const value = this.isNumber(params[0].value) ? this.formatNumber(params[0].value) : params[0].value
                    return `${params[0].name}: ${value}`
                  }
                },
                grid: {
                  top: 40,
                  bottom: 90,
                  left: '3%',
                  right: '4%',
                  containLabel: true
                },
                dataZoom: [{
                  type: 'slider',
                  show: true,
                  start: 0,
                  end: Math.min(100, Math.ceil(5 / tableData.length * 100)),
                  bottom: 10
                }, {
                  type: 'inside',
                  start: 0,
                  end: Math.min(100, Math.ceil(5 / tableData.length * 100))
                }],
                xAxis: {
                  type: 'category',
                  data: tableData.map(row => row[columns[0]]),
                  axisLabel: {
                    interval: 0,
                    rotate: 45,
                    color: '#666'
                  }
                },
                yAxis: {
                  type: 'value',
                  axisLabel: {
                    color: '#666',
                    formatter: (value) => {
                      return this.formatNumber(value)
                    }
                  }
                },
                series: [{
                  data: tableData.map(row => row[columns[numericColumnIndex]]),
                  type: 'bar',
                  barWidth: '40%',
                  barMaxWidth: 60,
                  barMinWidth: 15,
                  itemStyle: {
                  color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                      offset: 0,
                      color: '#83bff6'
                    }, {
                      offset: 1,
                      color: '#1890ff'
                    }]
                  },
                  borderRadius: [3, 3, 0, 0]
                },
                  emphasis: {
                    itemStyle: {
                      color: new echarts.graphic.LinearGradient(
                        0, 0, 0, 1,
                        [
                          {offset: 0, color: '#2378f7'},
                          {offset: 0.7, color: '#2378f7'},
                          {offset: 1, color: '#83bff6'}
                        ]
                      )
                    }
                  }
                }]
              }
              
              chart.setOption(option)
              this.charts.push(chart)
              
              window.addEventListener('resize', () => {
                chart.resize()
              })
            }
          })
        }
        
        // 滚动到底部显示新结果
        this.$nextTick(() => {
          const chatHistory = this.$refs.chatHistory
          if (chatHistory) {
            chatHistory.scrollTop = chatHistory.scrollHeight
          }
        })
      }
    }
  },
  
  beforeUnmount() {
    // 清理所有图表实例
    this.charts.forEach(chart => {
      if (chart) {
        chart.dispose()
      }
    })
    this.charts = []
  },

  created() {
    console.log('App 组件已加载');
    console.log('初始数据:', this.chatHistory, this.inspirations);
  }
}
</script>
<style>
body {
  margin: 0;
  padding: 0;
  background-color: #f0f5fa;  /* 浅蓝灰色背景 */
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.container {
  width: 90%;
  margin: 20px auto;
  height: calc(100vh - 40px);
}

.main-layout {
  display: flex;
  padding: 20px;
  gap: 20px;
  max-width: 1200px;
  margin: 0 auto;
  height: calc(100vh - 40px);
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0, 40, 130, 0.08);
  overflow: hidden;
}

/* 标题栏样式 */
.chat-header {
  padding: 20px;
  background: linear-gradient(135deg, #1e88e5, #1565c0);  /* 蓝色渐变 */
  color: #ffffff;
  text-align: center;
  position: relative;  /* 添加相对定位 */
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.chat-header h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
  color: #ffffff;
}

/* 聊天历史区域 */
.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #ffffff;
}

/* 用户消息样式 */
.user-message {
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  margin: 16px 0;
  gap: 12px;
}

.message-content {
  background: linear-gradient(135deg, #1e88e5, #1565c0);
  color: #ffffff;
  padding: 12px 16px;
  border-radius: 12px 12px 0 12px;
  max-width: 80%;
  font-size: 15px;
  box-shadow: 0 2px 6px rgba(30, 136, 229, 0.2);
}

/* 头像样式 */
.user-avatar, .ai-avatar {
  width: 40px;
  height: 40px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
  font-size: 16px;
  flex-shrink: 0;
}

.user-avatar {
  background: linear-gradient(135deg, #1e88e5, #1565c0);
  color: #ffffff;
  border: 1px solid #bbdefb;
}

.ai-avatar {
  background: #e3f2fd;
  color: #1565c0;
  border: 1px solid #bbdefb;
}

/* AI 回答样式 */
.ai-answer {
  display: flex;
  margin: 16px 0;
  gap: 12px;
  width: 90%;
}

.ai-answer .content {
  flex: 1;
  width: 100%;
  min-width: 0;  /* 允许内容区域收缩 */
}

.answer-box {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(30, 136, 229, 0.1);
  width: 100%;
  border: 1px solid #e3f2fd;
}

.answer-intro {
  color: #546e7a;
  font-size: 15px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e3f2fd;
}

/* 表格样式 */
.data-table {
  margin: 20px 0;  /* 与图表保持相同的上下边距 */
  width: 100%;     /* 占满容器宽度 */
  overflow-x: auto;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

table {
  width: 100%;
  border-collapse: collapse;
  min-width: 100%;
  white-space: nowrap;
}

th, td {
  padding: 12px 16px;
  text-align: center;  /* 改为居中对齐 */
  border-bottom: 1px solid #e2e8f0;
  vertical-align: middle;  /* 垂直居中 */
}

th {
  background-color: #f8fafc;
  font-weight: 500;
  color: #1e293b;
  white-space: nowrap;
}

td {
  background-color: #ffffff;
  color: #475569;
}

tr:last-child td {
  border-bottom: none;
}

tr:hover td {
  background-color: #f1f5f9;  /* 添加悬停效果 */
}

.message {
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 10px;
  padding: 20px;
  overflow: hidden;
  margin-bottom: 20px;
}

.chart-wrapper {
  margin: 20px 0;
  background: white;
  border-radius: 8px;
  border: 1px solid #e3f2fd;
  overflow: hidden;
  padding: 20px 0;  /* 移除左右内边距 */
}

.chart-container {
  width: 100%;
  height: 500px;
}

/* 输入区域样式 */
.input-area {
  padding: 20px;
  border-top: 1px solid #e3f2fd;
  display: flex;
  gap: 10px;
  background: #fff;
  align-items: center;  /* 确保垂直居中 */
  min-height: 60px;    /* 设置最小高度 */
}

.input-area input {
  flex: 1;
  height: 40px;        /* 固定高度 */
  padding: 0 15px;     /* 左右内边距 */
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  outline: none;       /* 移除焦点时的外边框 */
  transition: border-color 0.3s;
}

.input-area input:focus {
  border-color: #1976d2;  /* 焦时的边框颜色 */
}

.input-area button {
  height: 40px;        /* 与输入框同 */
  padding: 0 20px;     /* 左右内距 */
  background: #1976d2;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s;
  white-space: nowrap; /* 防止文字换行 */
}

.input-area button:hover {
  background: #1565c0;
}

/* 加载动画 */
.loading-box {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(30, 136, 229, 0.1);
  border: 1px solid #e3f2fd;
}

.loading-dots {
  display: flex;
  gap: 6px;
}

.loading-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #1e88e5;
  animation: bounce 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%, 80%, 100% { 
    transform: scale(0);
  } 
  40% { 
    transform: scale(1.0);
  }
}

/* 动条样式 */
.chat-history::-webkit-scrollbar {
  width: 8px;
}

.chat-history::-webkit-scrollbar-track {
  background: #f5f9ff;
}

.chat-history::-webkit-scrollbar-thumb {
  background: #bbdefb;
  border-radius: 4px;
}

.chat-history::-webkit-scrollbar-thumb:hover {
  background: #90caf9;
}

/* 添加数据展示区域的样式 */
.data-display {
  width: 100%;
  overflow-x: hidden;  /* 防止水平溢出 */
}

/* 当只有表格时的样式优化 */
.data-display:only-child .data-table {
  margin-bottom: 0;
}

.inspiration-panel {
  width: 280px;
  background-color: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0, 40, 130, 0.08);
  padding: 20px;
}

.inspiration-panel h3 {
  margin: 0 0 16px 0;
  color: #1565c0;
  font-size: 16px;
  font-weight: 500;
}

.inspiration-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.inspiration-item {
  padding: 12px 16px;
  background-color: #e3f2fd;  /* 浅蓝色背景 */
  border: 1px solid #bbdefb;  /* 蓝色边框 */
  border-radius: 8px;
  color: #1565c0;  /* 深蓝色文字 */
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.inspiration-item:hover {
  background-color: #bbdefb;  /* 更深的蓝色 */
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(46, 125, 50, 0.1);
}

/* 新增说明文字样式 */
.data-note {
  color: #78909c;
  font-size: 13px;
  margin-bottom: 12px;
  padding-left: 4px;
}

.prompt-button {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 10px 20px;
  background: #1e88e5;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.prompt-button:hover {
  background: #1565c0;
  transform: translateY(-2px);
}

.config-panel {
  background: #1976d2;  /* 使用单一的蓝色背景 */
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0, 40, 130, 0.08);
  padding: 20px;
}

.config-panel h3 {
  margin: 0 0 16px 0;
  color: #FFFFFF;
  font-size: 16px;
  font-weight: 500;
}

.config-content {
  display: flex;
  flex-wrap: wrap;  /* 允许按钮换行 */
  gap: 12px;  /* 按钮之间的间距 */
  padding: 0 10px;
}

.config-button {
  flex: 1 1 calc(50% - 6px);  /* 每行两个按钮，考虑间距 */
  min-width: 120px;
  padding: 12px 16px;
  background-color: #e3f2fd;
  border: 1px solid #bbdefb;
  border-radius: 8px;
  color: #1565c0;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.config-button:hover {
  background-color: #bbdefb;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(21, 101, 192, 0.1);
}

.side-panels {
  display: flex;
  flex-direction: column; /* 纵向排列 */
  gap: 20px; /* 面板之间的间距 */
  width: 300px; /* 设置侧边面板的宽度 */
}

.config-panel, .inspiration-panel {
  background-color: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0, 40, 130, 0.08);
  padding: 20px;
}

.inspiration-panel h3, .config-panel h3 {
  margin: 0 0 16px 0;
  color: #1565c0;
  font-size: 16px;
  font-weight: 500;
}

.inspiration-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.inspiration-item {
  padding: 12px 16px;
  background-color: #e3f2fd;
  border: 1px solid #bbdefb;
  border-radius: 8px;
  color: #1565c0;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.inspiration-item:hover {
  background-color: #bbdefb;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(21, 101, 192, 0.1);
}

.input-area button:disabled {
  background: #cccccc;
  cursor: not-allowed;
  opacity: 0.7;
}

.input-area input:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.answer-box {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.data-display {
  margin-top: 16px;
  max-height: 320px;  /* 限制表格高度 */
  overflow-y: auto;   /* 允许垂直滚动 */
  border: 1px solid #e2e8f0;
  border-radius: 6px;
}

.data-display table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;  /* 减小字体大小 */
}

.data-display thead {
  position: sticky;  /* 表头固定 */
  top: 0;
  background: #f8fafc;
  z-index: 1;
}

.data-display th {
  padding: 8px 12px;
  text-align: center;  /* 改为居中对齐 */
  font-weight: 600;    /* 加粗字体 */
  color: #1e293b;
  border-bottom: 1px solid #e2e8f0;
  white-space: nowrap;
  background: #f8fafc;  /* 确保背景色一致 */
}

.data-display td {
  padding: 6px 12px;
  border-bottom: 1px solid #e2e8f0;
  color: #475569;
  text-align: center;  /* 可选：让数据也居中对齐 */
}

.data-display tr:last-child td {
  border-bottom: none;
}

.data-display tbody tr:hover {
  background-color: #f1f5f9;
}

/* 自定义滚动条样式 */
.data-display::-webkit-scrollbar {
  width: 6px;
}

.data-display::-webkit-scrollbar-track {
  background: #f1f5f9;
}

.data-display::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.data-display::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

.loading-text {
  color: #666;
  margin-right: 12px;
  font-size: 14px;
}

.loading-box {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 16px;
}

.ambiguous-box {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(30, 136, 229, 0.1);
  border: 1px solid #e3f2fd;
}

.ambiguous-intro {
  color: #546e7a;
  font-size: 15px;
  margin-bottom: 16px;
}

.ambiguous-item {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.term-label {
  font-weight: 500;
  color: #1565c0;
  margin-right: 12px;
  min-width: 80px;
}

.options-list {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.option-button {
  padding: 6px 12px;
  border: 1px solid #bbdefb;
  border-radius: 6px;
  background-color: #ffffff;
  color: #1976d2;
  cursor: pointer;
  transition: all 0.2s ease;
}

.option-button:hover {
  background-color: #e3f2fd;
}

.option-button.selected {
  background-color: #1976d2;
  color: #ffffff;
  border-color: #1976d2;
}

.confirm-button {
  margin-top: 16px;
  padding: 8px 16px;
  background-color: #1976d2;
  color: #ffffff;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.confirm-button:hover {
  background-color: #1565c0;
}

.confirm-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style>
